package org.blogwu.learn.designpattern.chapter8.lazy.v5;

import java.lang.reflect.InvocationTargetException;

/**
 * 注重延迟加载，加入volatile防止重排序
 */
public class LazyDoubleCheckSingleton {
    private LazyDoubleCheckSingleton() {
        if (fla) {
            throw new RuntimeException("禁止反射");
        }
    }

    // 实例化标志位，主要是防止反射生成第二个对象实例。这生成玩第一个后就会设置为false；
    private static boolean fla = true;

    private static volatile LazyDoubleCheckSingleton lazySingleton;

    public static LazyDoubleCheckSingleton getInstance() throws InterruptedException {
        //外面做一层判断，是为了单例实例化后，不在需要进入同步方法了。 
        if (lazySingleton == null) {
            synchronized (LazyDoubleCheckSingleton.class) {
                if (lazySingleton == null) {
                    fla = false;
//                    Thread.sleep(2000);
                    lazySingleton = new LazyDoubleCheckSingleton();
                    fla = true;
                }
            }
        }
        return lazySingleton;
    }


    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, InterruptedException {
//        Class cl=LazyDoubleCheckSingleton.class;
//        Constructor<LazyDoubleCheckSingleton> cc=cl.getDeclaredConstructor();
//        cc.setAccessible(true);
//        LazyDoubleCheckSingleton newlazyDoubleCheckSingleton=cc.newInstance();
//        System.out.println("newlazyDoubleCheckSingleton:"+newlazyDoubleCheckSingleton);
        LazyDoubleCheckSingleton lazyDoubleCheckSingleton = LazyDoubleCheckSingleton.getInstance();

        System.out.println("lazyDoubleCheckSingleton:" + lazyDoubleCheckSingleton);

    }

}
